package com.wang.nowcoder.controller;

import com.wang.nowcoder.annotation.LoginRequired;
import com.wang.nowcoder.pojo.User;
import com.wang.nowcoder.service.FollowService;
import com.wang.nowcoder.service.LikeService;
import com.wang.nowcoder.service.UserService;
import com.wang.nowcoder.util.CommunityConstant;
import com.wang.nowcoder.util.CommunityUtil;
import com.wang.nowcoder.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author wang
 * @ClassName UserController
 * @Description 用户设置
 * @date 2021/12/20 20:33
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @LoginRequired
    @RequestMapping("/setting")
    public String userSet() {
        return "/site/setting";
    }

    /**
     * 更新存放头像
     *
     * @param headerImage
     * @param model
     * @return
     */
    @LoginRequired
    @RequestMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片");
            return "/site/setting";
        }
//        获取原始文件名
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }
//        生成随机文件名
        filename = CommunityUtil.generateUUID() + suffix;
        //确认文件存放路径
        File file = new File(uploadPath + "/" + filename);
        try {
            headerImage.transferTo(file);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常", e);
        }

        //更新当前用户的头像的路径(web访问路径)
        User user = hostHolder.getUser();
        //将头像路径设为http://localhost/user/header/xxx.png
        String headerUrl = domain + "/user/header/" + filename;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    /**
     * 获取头像
     *
     * @param fileName
     * @param response
     */
    @RequestMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image" + suffix);
        try (
                OutputStream outputStream = response.getOutputStream();
                FileInputStream fileInputStream = new FileInputStream(fileName);
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败" + e.getMessage());
        }
    }

    /**
     * 更新密码
     * @return
     */
    @LoginRequired
    @PostMapping("/updatePwd")
    public String updatePwd(@CookieValue("ticket") String ticket, String password, String newPasswordTwo,Model model, String newPassword){
        //进行空值判断
        if (password == null){
            model.addAttribute("pwdMsg","请输入密码");
            return "/site/setting";
        }
        User user = hostHolder.getUser();
        password = CommunityUtil.md5(password+user.getSalt());
        if (!user.getPassword().equals(password)){
            model.addAttribute("pwdMsg","密码错误");
            return "/site/setting";
        }
        password = CommunityUtil.md5(newPassword+user.getSalt());
        //进行新旧密码判断
        if (user.getPassword().equals(password)){
            model.addAttribute("pwdMsg2","新旧密码相同,请重新输入");
            return "/site/setting";
        }else if (!newPassword.equals(newPasswordTwo)){
            model.addAttribute("pwdMsg3","两次密码不相同,请重新输入");
            return "/site/setting";
        } else {
            userService.updatePassword(user.getId(),password);
            userService.loginOut(ticket);
            return "redirect:/login";
        }
    }

    /**
     * 用户个人主页
     * @param userId
     * @param model
     * @return
     */
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId,Model model){
        User user = userService.selectById(userId);
        if (user == null){
            throw new RuntimeException("该用户不存在");
        }
        //用户
        model.addAttribute("user",user);
        //点赞数量
        int likeCount = likeService.selectUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);

        //关注数量
        long followCount = followService.selectFollowCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followCount",followCount);
        //粉丝数量
        long followerCount = followService.selectFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        //是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser()!=null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";
    }
}
